//
//  AYuUITabBar.swift
//  SHWeibo3
//
//  Created by 余伟康 on 16/7/19.
//  Copyright © 2016年 wangce. All rights reserved.
//
//  自定义tabBar 添加中间加号按钮

import UIKit
// 声明协议

// 使用weak 修饰 需要继承NSObjectProtocol
protocol AYuTabBarDelegate:NSObjectProtocol{
    // 协议方法
    func composeButtonClick()
}

class AYuUITabBar: UITabBar {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    func setupUI(){
        // 添加控件
        addSubview(composeButton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 计算各控件位置
        let w = frame.width * 0.2
        var index:CGFloat = 0
        
        for value in subviews{
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                value.frame.origin.x = index * w
                value.frame.size.width = w
                
                index++
                if index == 2{
                    index++
                }
            }
        }
        composeButton.center.x = frame.width * 0.5
        composeButton.center.y = frame.height * 0.5
    }
    
    // MARK: - 懒加载控件
    lazy var composeButton : UIButton = {
        let button = UIButton()
        // 添加点击事件
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Normal)
        button.sizeToFit()
        return button
    }()
    
    // MARK: - 监听方法
    
    // 声明代理
    weak var AYuDelegate:AYuTabBarDelegate?
    
    func buttonClick(){
        AYuDelegate?.composeButtonClick()
    }

}
